<template>
  <view class="cs-btn-grid">
    <wd-row
      v-for="(rowItems, rowIndex) in chunkItems"
      class="cs-btn-grid_row"
      :key="`row_${rowIndex}`"
    >
      <wd-col
        v-for="(colItem, colItemIndex) in rowItems"
        :span="2"
        :offset="colItemIndex > 0 ? 2 : 1"
        :custom-class="`${rowIndex > 0 ? 'mt-2' : ''}`"
        :key="`col_${rowIndex}_${colItemIndex}`"
      >
        <CsIcon
          :icon="colItem.icon"
          :icon-prefix="colItem.iconPrefix"
          :size="colItem.size"
          :text="colItem.title"
          :is-active="rowIndex === activeIcon.rowIndex && colItemIndex === activeIcon.colIndex"
          :show-more="colItem.children?.length > 0"
          color="#ffffff"
          @click="iconClick(rowIndex, colItemIndex)"
        />
      </wd-col>
    </wd-row>
  </view>
</template>

<script lang="ts" setup>
import { chunk } from 'lodash'
import CsIcon from '../cs-icon/cs-icon.vue'
import { COL_MAXIMUM } from './cs-btn-grid.constants'
import { CsGridItem } from './cs-btn-grid.types'

defineOptions({
  name: 'cs-btn-grid',
  options: {
    virtualHost: true,
    styleIsolation: 'shared',
  },
})

const props = withDefaults(
  defineProps<{
    column?: number
    items: CsGridItem[]
  }>(),
  {
    column: COL_MAXIMUM,
  },
)

const items = toRef(props, 'items')

const emit = defineEmits<{ click: [item: CsGridItem] }>()

const activeIcon = ref<{
  rowIndex: number
  colIndex: number
}>({
  rowIndex: 0,
  colIndex: 0,
})

const chunkItems = computed(() =>
  chunk(items.value, props.column > COL_MAXIMUM ? COL_MAXIMUM : props.column),
)

watch(chunkItems, (newChunkItems) => {
  console.log('chunkItems', newChunkItems)
})

const iconClick = (rowIndex: number, colIndex: number) => {
  activeIcon.value = {
    rowIndex,
    colIndex,
  }

  emit('click', chunkItems.value[rowIndex][colIndex])
}

console.log('chunkItems', chunkItems.value)
</script>

<style lang="scss" scoped></style>
